﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AiLuWeb.WebSite.Code;
using Ajeelee.Core.Utils;
using System.Configuration;
using System.Web.Security;
using AiLuWeb.Business;
using AiLuWeb.Model;
using System.Collections;

namespace AiLuWeb.WebSite.WebAdmin 
{
    public partial class login : PageBase
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (IsPost)
            {
                Login();
            }
        }

        private void Login()
        {
            string uname = FormParam("username");
            string pwd = FormParam("password").MD5Secret();
            string vcode = FormParam("verifycode").Trim().ToLower().SimpleEncryp();

            if (vcode != Request.Cookies["VLCode"].Value)
            {
                Response.Write("<script>alert('验证码输入有误!');</script>");
                return;
            }
            SetCookie("VLCode", null, DateTime.Now.AddDays(-30));
            if (uname == ConfigurationManager.AppSettings["SuperuserName"])
            {
                //超级用户登陆验证
                if (pwd != ConfigurationManager.AppSettings["SuperuserPwd"])
                {
                    Response.Write("<script>alert('密码错误!');</script>");
                }
                else
                {
                    //超级用户登陆成功
                    //1.保存验证票据
                    FormsAuthentication.SetAuthCookie(uname, false);
                    //2.页面跳转
                    FormsAuthentication.RedirectFromLoginPage(uname, false);
                }
            }
            else
            {
                IUAdministratorBusiness userBll = new UAdministratorBusinessFactory().CreateUAdministratorBusiness();
                Hashtable table = new Hashtable();
                table.Add(UAdministratorHash.Name, uname);
                table.Add(UAdministratorHash.Pwd, pwd);
                IList<UAdministrator> uadmin = userBll.GetAllUAdministrator(table);
                if (uadmin.Count> 0)
                {
                    //保存验证票据
                    FormsAuthentication.SetAuthCookie(uname, false);
                    //页面跳转
                    FormsAuthentication.RedirectFromLoginPage(uname, false);
                    
                    //更新用户登录信息
                    UAdministrator user = uadmin.FirstOrDefault();
                    user.LoginCounts = user.LoginCounts + 1;
                    user.LoginIP = Function.GetIPAddress();
                    user.LoginTime = DateTime.Now;
                    userBll.Update(user);
                }
                else
                {
                    Response.Write("<script>alert('用户名或密码错误!');</script>");
                }
            }
        }
    }
}